import uuid

from app import db
from datetime import datetime

def generate_uuid16():
    """
    生成一个16位数字字符串：
    通过将 uuid4 生成的整数对 10**16 取余，并格式化为16位，不足前面补0。
    """
    return f"{uuid.uuid4().int % (10**16):016d}"

class UserTopicAssociation(db.Model):
    __tablename__ = 'user_topic_association'

    id = db.Column(db.String(255), primary_key=True,default=generate_uuid16)
    user_id = db.Column(db.String(255), db.ForeignKey('users.id'), nullable=False)
    topic_id = db.Column(db.String(255), nullable=False)
    create_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    title = db.Column(db.String(255), nullable=False)
    types = db.Column(db.String(255), nullable=False)

    def __repr__(self):
        return f"<UserTopicAssociation(id={self.id}, user_id='{self.user_id}', topic_id='{self.topic_id}', title='{self.title}', types='{self.types}')>"

    def to_dict(self):
        return {
            "id": self.id,
            "user_id": self.user_id,
            "topic_id": self.topic_id,
            "create_at": self.create_at.isoformat(),
            "title": self.title,
            "types": self.types
        }

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def update_from_db(self):
        db.session.commit()